//
//  IWObjectFinder.m
//  aPlanner
//
//  Created by Daniel Braun on 01/09/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "IWObjectFinder.h"


@implementation IWObjectFinder

- (id) contentForPath:(NSString *)s parameters:(NSArray *)params
	   variables:(NSDictionary*)dp  info:(id <HttpdInformation>) br
{
	NSArray *pe=[s pathComponents];
	if ([pe count]<3) return nil;
	if (![[pe objectAtIndex:0] isEqualToString:@"/"]) return nil;
	if (![[pe objectAtIndex:1] isEqualToString:@"IWO"]) return nil;
	NSString *docName=[pe objectAtIndex:2];
	
	NSDocumentController *dc=[NSDocumentController sharedDocumentController];
	if (!dc) return nil;
	NSArray *docs=[dc documents];
	unsigned int i, count = [docs count];
	NSDocument *mydoc=nil;
	for (i = 0; i < count; i++) {
		NSDocument * d = [docs objectAtIndex:i];
		NSLog(@"got doc %@ / %@\n", d, [d displayName]);
		if ([[d displayName] isEqualToString:docName]) {
			mydoc=d;
			break;
		}
	}
	if (!mydoc) return nil;
	id myobj=nil;
	count = [pe count];
	for (i = 3, myobj=mydoc; i < count; i++) {
		if (![accessControl canTraverseObject:myobj info:br]) return nil; 
		NSString * k = [pe objectAtIndex:i];
		if ([k isEqualToString:@"/"]) continue;
		if ([k hasPrefix:@"-"]) {
			k=[k substringFromIndex:1];
			SEL s=sel_registerName([k cString]);
			if (s) {
				if (![accessControl canPerform:s 
						      onObject:myobj
							  info:br]) return nil;
				// should check signature of s, and verify
				// s returns an object
				NSMethodSignature *ms=[myobj methodSignatureForSelector:s];
				if (!ms) return nil;
				const char *r=[ms methodReturnType];
				if (strcmp(r, "@")) return nil;
				myobj=[myobj performSelector:s];
				continue;
			} else return nil;
		}
		@try {
			myobj=[myobj valueForKey:k];
		}
		@catch (NSException *ex) {
			myobj=nil;
		}
		@finally {
		}
		if (!myobj) return nil;
		if (![accessControl canTraverseObject:myobj info:br]) return nil; 
	}
	
	if (params ) {
		int pc=[params count];
		if (pc<2) return nil;
		NSString *verb=[params objectAtIndex:0];
		NSString *key=[params objectAtIndex:1];
		if ([verb isEqualToString:@"set"]) {
			BOOL ok;
			NSString *val=[params objectAtIndex:2];
			if (pc<3) return nil;
			if (![accessControl canSetKey:key onObject:myobj info:br]) return nil;
			@try {
				ok=YES;
				[myobj setValue:val forKey:key];
			}
			@catch  (NSException *ex) {
				ok=NO;
			}
			@finally {
			}
			return ok ? @"ok" : @"failed";
		}
		return nil;
	}
	
	NSString *sel1=[dp objectForKey:@"sel"];
	id result=nil;
	SEL sel=@selector(description);
	if (sel1) sel=sel_registerName([sel1 cString]);
	else if ([myobj respondsToSelector:@selector(htmlView)]) sel=@selector(htmlView);
	if (![myobj respondsToSelector:sel]) return nil;
	if (![accessControl canPerform:sel onObject:myobj info:br]) return nil;
	result=[myobj performSelector:sel];
	
	return result;
	
}

@end
